package org.compiere.process;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import org.compiere.model.MClient;
import org.compiere.model.MMailText;
import org.compiere.model.MUser;
import org.compiere.model.X_CMS_Contract;
import org.compiere.model.X_C_BPartner;
import org.compiere.model.X_R_MailText;
import org.compiere.model.X_cms_agreement;
import org.compiere.util.DB;
import org.compiere.util.EMail;
import org.compiere.util.Env;

public class CMS_SendMail extends SvrProcess {

	@Override
	protected void prepare() {
		
	}

	@Override
	protected String doIt() throws Exception {
		SendMail();
		return null;
	}
	
	private boolean SendMail() throws Exception
	{
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		X_cms_agreement agreement = new X_cms_agreement(getCtx(),getRecord_ID(),get_TrxName());
		
		String sql = "SELECT Signer FROM adempiere.CMS_Agreement_Line WHERE CMS_Agreement_ID = " + agreement.get_ID();
		
		ArrayList<Integer> index = new ArrayList<Integer>();
		
		try 
		{
			pstmt = DB.prepareStatement(sql, get_TrxName());
			rs = pstmt.executeQuery();
			
			while(rs.next()) 
			{
				index.add(rs.getInt(1));
			}
		}
		catch (Exception e) {}
		finally
		{
			DB.close(rs, pstmt);
			rs = null; pstmt = null;
		}

		
		if(index.size() == 0)
			throw new Exception("Unable to load list of signers");
					
		X_R_MailText rText = new X_R_MailText(getCtx(), null, get_TrxName());
		
		X_CMS_Contract contract = new X_CMS_Contract(getCtx(),agreement.getCMS_Contract_ID(), get_TrxName());
		
		String message = "Вам необходимо рассмотреть и согласовать проект договора";
		message += "\n\n" + "Номер карточки договора:  " + contract.getDocumentNo();
		message += "\n\n" + "Предмет договора: " + contract.getDescription();
		message += "\n\r" + "Метка согласования: " + agreement.getName();

		int C_BPartner_ID = agreement.getC_BPartner_ID();
		
		if(C_BPartner_ID == -1)
			throw new Exception("Unable to send message. C_BPartner is not filled");
		
		String userName = (new X_C_BPartner(getCtx(), C_BPartner_ID, get_TrxName())).getName();
		
		if(userName == "")
			userName = "Unknown";
		
		rText.setMailHeader("Согласование");
		rText.setMailText(message);
		rText.setName(userName);
		
		if(!rText.save())
			throw new Exception("Unnable to save mail pattern");
		
		MMailText mailText = new MMailText(getCtx(), rText.get_ID(), get_TrxName());						
		
		String sqlGetZerdeAdmin = "select max(ad_user_id) from ad_user where lower(name) like '%zerdea%'";
		
		int p_AD_User_ID = DB.getSQLValue(get_TrxName(), sqlGetZerdeAdmin);		
		
		if(p_AD_User_ID < 0)
			throw new Exception("User_ID not found");
		
		int p_AD_Client_ID = Env.getAD_Client_ID(getCtx());
		
		MUser userFrom = new MUser(getCtx(), p_AD_User_ID, get_TrxName());
		MUser userTo = null;		
		MClient client = new MClient(getCtx(), p_AD_Client_ID, get_TrxName());		
		
		for(int i = 0; i < index.size(); i++) 
		{		
			userTo = new MUser(getCtx(), index.get(i), get_TrxName());
		
			EMail mail = client.createEMail(userFrom, userTo, mailText.getMailHeader(), mailText.getMailText());
		
			EMail.SENT_OK.equals(mail.send());
		}
		return true;
	}

}
